package net.hserver.apm.config;

import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import cn.hserver.core.ioc.annotation.Bean;
import cn.hserver.core.ioc.annotation.Configuration;
import cn.hserver.core.ioc.annotation.Value;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author hxm
 */
@Configuration
public class MongodbConfig {

    public final static String DATA_BASE = "apm";

    @Value("apm.mongodb.ip")
    private String ip;

    @Value("apm.mongodb.port")
    private int port;

    @Value("apm.mongodb.username")
    private String username;

    @Value("apm.mongodb.password")
    private String password;

    @Bean
    public MongoClient initMongoClient() {
        if (username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0) {
            return new MongoClient(ip, port);
        }
        MongoCredential credential = MongoCredential.createCredential(username, DATA_BASE, password.toCharArray());
        //封装MongoDB的地址和端口
        ServerAddress address = new ServerAddress(ip, port);
        //方法过时是由于现在推荐池连的方式
        return new MongoClient(address, Collections.singletonList(credential));
    }

}
